package com.rmfyzxfw.caseprocess.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.rmfyzxfw.caseprocess.mapper.FymcMapper;
import com.rmfyzxfw.caseprocess.model.converter.CourtConverter;
import com.rmfyzxfw.caseprocess.model.po.Fymc;
import com.rmfyzxfw.caseprocess.model.vo.CourtVO;
import com.rmfyzxfw.caseprocess.service.FymcService;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author GYW
 * @description 针对表【t_fymc(法院信息综合表)】的数据库操作Service实现
 * @createDate 2024-09-06 11:10:05
 */
@Service
@RequiredArgsConstructor
public class FymcServiceImpl extends ServiceImpl<FymcMapper, Fymc>
        implements FymcService {
    private final CourtConverter courtConverter;
    private static FymcMapper fymcMapper;
    public static final String courtsTreeKey = "courtsTreeKey";

    @Autowired
    public void setFymcMapper(FymcMapper fymcMapper) {
        FymcServiceImpl.fymcMapper = fymcMapper;
    }

    public static final LoadingCache<String, List<CourtVO>> courtsCache;

    static {
        courtsCache = CacheBuilder.newBuilder()
                //设置并发级别为8，并发级别是指可以同时写缓存的线程数
                .concurrencyLevel(8)
                //设置写缓存后5分钟过期
                .expireAfterWrite(5, TimeUnit.MINUTES)
                //设置缓存容器的初始容量为10
                .initialCapacity(200)
                //设置缓存最大容量为100，超过100之后就会按照LRU最近虽少使用算法来移除缓存项
                .maximumSize(2000)
                //设置要统计缓存的命中率
                .recordStats()
                .refreshAfterWrite(Duration.ofSeconds(30L)) // 30s刷新一次
                //build方法中可以指定CacheLoader，在缓存不存在时通过CacheLoader的实现自动加载缓存
                .build(
                        new CacheLoader<String, List<CourtVO>>() {
                            @NotNull
                            @Override
                            public List<CourtVO> load(@NotNull String key) {
                                if (!courtsTreeKey.equals(key)) {
                                    return Collections.EMPTY_LIST;
                                }

                                return buildCourtsTree();
                            }
                        }
                );
    }

    @Override
    public List<CourtVO> allCourts() {
        try {
            return courtsCache.get(courtsTreeKey);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }


    private static List<CourtVO> buildCourtsTree() {
        List<Fymc> list = fymcMapper.selectList(Wrappers.lambdaQuery());
        List<CourtVO> courtVOS = CourtConverter.INSTANCE.dos2vos(list);

        Map<String, List<CourtVO>> courtVOMap = courtVOS.stream().filter(courtVO -> !"0000".equals(courtVO.getSjfydmHy())).collect(Collectors.groupingBy(CourtVO::getSjfydmHy));
        courtVOS.forEach(c -> c.setChildrenCourts(courtVOMap.get(c.getFydmHy())));
        List<CourtVO> tree = courtVOS.stream().filter(courtVO -> "0000".equals(courtVO.getSjfydmHy())).collect(Collectors.toList());

//        List<CourtVO> makeTree = TreeUtil.makeTree(courtVOS, c -> "0000".equals(c.getSjfydmHy()), (x, y) -> x.getFydmHy().equals(y.getSjfydmHy()), CourtVO::setChildrenCourts);
        return tree;
    }
}




